package com.xyoto.takeawayUser.utils;

import io.minio.*;
import net.coobird.thumbnailator.Thumbnails;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

/**
 * minio上传文件实现类
 *
 * @author Administrator
 */
@Service
@Component
public class MinioUtils implements Minio {

    public static String URL = "http://10.60.36.66:9000";
    public static String URL1 = "http://minio.wyoto.cn";
    public static String AccessKey = "minioadmin";
    public static String SecretKey = "minioadmin";
    public static String bucketName = "wywm";

    /**
     * 单例实现minio实例
     */
    public static class MinioClientHolder {
        private static MinioClient minio;

        static {
            try {
                minio = MinioClient.builder()
                        .endpoint(URL)
                        .credentials(AccessKey, SecretKey)
                        .build();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 获取minio实例
     *
     * @return
     */
    private static MinioClient getMinio() {
        return MinioClientHolder.minio;
    }

    /**
     * 单文件上传
     *
     * @param file      文件
     * @param mouldName 模块名
     * @return 文件路径
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file, String mouldName) throws Exception {
        try {
            MinioClient minio = getMinio();
            boolean exists = minio.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) {
                minio.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }

            File compress = compress(file);
            FileInputStream inputStream = new FileInputStream(compress);
            MultipartFile file1 = new MockMultipartFile(compress.getName(), inputStream);

            String uuid = UUID.randomUUID().toString().replace("-", "");
            String filename = new DateTime().toString("yyyy-MM-dd HH:mm:ss") + " "
                    + uuid
                    + Objects.requireNonNull(file.getOriginalFilename())
                    .substring(file.getOriginalFilename().lastIndexOf("."));

            String dataPath =  mouldName + "/" + new DateTime().toString("yyyy/MM/dd") + "/" + filename;

            minio.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(dataPath)
                            .stream(file1.getInputStream(), file1.getSize(), 10 * 1024 * 1024)
                            .contentType(file.getContentType())
                            .build());


            if (!compress.delete()) {
                MinioUtils minioUtils = new MinioUtils();
                minioUtils.removeFile(dataPath);
                throw new RuntimeException();
            }
            return URL1 + "/" + bucketName + "/" + dataPath;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 文件上传
     * 支持单文件，多文件上传
     *
     * @param mouldName 模块名
     * @param files     文件
     * @return 文件路径
     * @throws Exception
     */
    @Override
    public String uploadFiles(String mouldName, MultipartFile... files) throws Exception {

        if (files.length < 1) {
            throw new RuntimeException("上传文件为空");
        }
        StringBuilder builder = new StringBuilder();
        for (MultipartFile file : files) {
            builder.append(uploadFile(file, mouldName));
            builder.append(",");
        }

        return builder.deleteCharAt(builder.length() - 1).toString();
    }

    /**
     * 删除文件
     *
     * @param url 文件路径
     * @return
     * @throws Exception
     */
    @Override
    public Boolean removeFile(String url) {
        try {
            MinioClient minio = getMinio();
            String replace = url.replace(URL1 + "/" + bucketName + "/"  , "");
            minio.removeObject(
                    RemoveObjectArgs.builder()
                            .bucket(bucketName)
                            .object(replace)
                            .build());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 文件压缩
     *
     * @param file 文件
     * @throws Exception
     */
    public static File compress(MultipartFile file) throws Exception {

        UUID uuid = UUID.randomUUID();
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        File upload = new File(ClassUtils
                .getDefaultClassLoader()
                .getResource("")
                .getPath() + uuid + "." + suffix
        );
        if (file.getSize() >= (1024 * 1024 * 0.1)) {
            Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.3f).toFile(upload);
        } else if ((1024 * 1024) < file.getSize() && file.getSize() <= (1024 * 1024 * 2)) {
            Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.2f).toFile(upload);
        } else {
            Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.1f).toFile(upload);
        }
        return upload;
    }

}
